package com.atguigu.yygh.user.service.impl;

import com.atguigu.yygh.common.JwtHelper;
import com.atguigu.yygh.enums.AuthStatusEnum;
import com.atguigu.yygh.exception.MyException;
import com.atguigu.yygh.model.user.Patient;
import com.atguigu.yygh.model.user.UserInfo;
import com.atguigu.yygh.user.mapper.UserInfoMapper;
import com.atguigu.yygh.user.service.PatientService;
import com.atguigu.yygh.user.service.UserInfoService;
import com.atguigu.yygh.vo.user.LoginVo;
import com.atguigu.yygh.vo.user.UserAuthVo;
import com.atguigu.yygh.vo.user.UserInfoQueryVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.cache.CacheProperties;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper,UserInfo> implements UserInfoService {
    @Autowired
    RedisTemplate<String,String> redisTemplate;
    @Autowired
    PatientService patientService;

    @Override
    public Map<String, Object> login(LoginVo loginVo) {

        //校验参数
        String phone = loginVo.getPhone();
        String code = loginVo.getCode();
        String openid = loginVo.getOpenid();
        if (StringUtils.isEmpty(phone) || StringUtils.isEmpty(code)){
            throw new MyException(20001,"账号密码为空");
        }
        //TODO 校验校验验证码
        String code1 = redisTemplate.opsForValue().get(loginVo.getPhone());
        if (!code1.equals(code)){
            throw new MyException(20001,"验证码失败");
        }
        Map<String,Object> map=new HashMap<>();
        if (StringUtils.isEmpty(openid)){
            //手机号已被使用
            QueryWrapper<UserInfo> wrapper =new QueryWrapper();
            wrapper.eq("phone",phone);
            UserInfo userInfo = baseMapper.selectOne(wrapper);
            if (userInfo==null){
                userInfo=new UserInfo();
                userInfo.setPhone(phone);
                userInfo.setStatus(1);
                baseMapper.insert(userInfo);
            }
            //获取会员
            //校验是否被禁用
            if (userInfo.getStatus()!=1){
                throw new MyException(20001,"用户已经禁用");
            }
            map=this.get(userInfo);
        }else {
            QueryWrapper<UserInfo> wrapper=new QueryWrapper<>();
            wrapper.eq("phone",phone);
            UserInfo userInfo = baseMapper.selectOne(wrapper);
            QueryWrapper<UserInfo> wrapper1=new QueryWrapper<>();
            wrapper1.eq("openid",openid);
            UserInfo userInfoWx  = baseMapper.selectOne(wrapper1);
            if (userInfo!=null){
                userInfoWx.setName(userInfo.getName());
                userInfoWx.setAuthStatus(userInfo.getAuthStatus());
                userInfoWx.setCertificatesNo(userInfo.getCertificatesNo());
                userInfoWx.setCertificatesType(userInfo.getCertificatesType());
                userInfoWx.setCertificatesUrl(userInfo.getCertificatesUrl());
                baseMapper.delete(wrapper);
            }
            userInfoWx .setPhone(phone);
            baseMapper.updateById(userInfoWx );
            if (userInfoWx .getStatus()!=1){
                throw new MyException(20001,"用户已经禁用");
            }
            map=this.get(userInfoWx );
        }
        //返回页面显示名称r
        return map;
    }

    private Map<String, Object> get(UserInfo userInfo) {
        Map<String,Object> map=new HashMap<>();
        String name = userInfo.getName();
        if(StringUtils.isEmpty(name)){
            name = userInfo.getNickName();
        }
        if(StringUtils.isEmpty(name)) {
            name = userInfo.getPhone();
        }
        map.put("name", name);
        String token = JwtHelper.createToken(userInfo.getId(), name);
        map.put("token", token);
        return map;
    }

    @Override
    public UserInfo selectWxInfoOpenId(String openid) {
        QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("openid",openid);
        UserInfo userInfo = baseMapper.selectOne(wrapper);
        return userInfo;
    }

    @Override
    public void userAuth(Long userId, UserAuthVo userAuthVo) {
        UserInfo userInfo = baseMapper.selectById(userId);
        BeanUtils.copyProperties(userAuthVo,userInfo);
        userInfo.setAuthStatus(AuthStatusEnum.AUTH_RUN.getStatus());
        baseMapper.updateById(userInfo);
    }

    @Override
    public IPage<UserInfo> selectPage(Page<UserInfo> pageParam, UserInfoQueryVo userInfoQueryVo) {
        //UserInfoQueryVo获取条件值
        String name = userInfoQueryVo.getKeyword(); //用户名称
        Integer status = userInfoQueryVo.getStatus();//用户状态
        Integer authStatus = userInfoQueryVo.getAuthStatus(); //认证状态
        String createTimeBegin = userInfoQueryVo.getCreateTimeBegin(); //开始时间
        String createTimeEnd = userInfoQueryVo.getCreateTimeEnd(); //结束时间
        QueryWrapper<UserInfo> wrapper=new QueryWrapper<>();
        if (!StringUtils.isEmpty(name)){
            wrapper.like("name",name);
        }
        if (!StringUtils.isEmpty(status)){
            wrapper.eq("status",status);
        }
        if(!StringUtils.isEmpty(authStatus)) {
            wrapper.eq("auth_status",authStatus);
        }
        if(!StringUtils.isEmpty(createTimeBegin)) {
            wrapper.ge("create_time",createTimeBegin);
        }
        if(!StringUtils.isEmpty(createTimeEnd)) {
            wrapper.le("create_time",createTimeEnd);
        }
        IPage<UserInfo> Pages = baseMapper.selectPage(pageParam, wrapper);
        Pages.getRecords().stream().forEach(item->{
            this.packageUserInfo(item);
        });
        return Pages;
    }

    @Override
    public void lock(Long userId, Integer status) {
        if (status.intValue()==0||status.intValue()==1){
            UserInfo userInfo = baseMapper.selectById(userId);
            userInfo.setStatus(status);
            baseMapper.updateById(userInfo);
        }

    }

    @Override
    public Map<String, Object> show(Long userId) {
        UserInfo userInfo = this.packageUserInfo(baseMapper.selectById(userId));
        List<Patient> patientList=patientService.findAll(userId);
        Map<String,Object> map=new HashMap<>();
        map.put("userInfo",userInfo);
        map.put("patientList",patientList);
        return map;
    }

    @Override
    public void approval(Long userId, Integer authStatus) {
        if (authStatus.intValue()==2||authStatus==-1){
            UserInfo userInfo = baseMapper.selectById(userId);
            userInfo.setAuthStatus(authStatus);
            baseMapper.updateById(userInfo);
        }

    }

    private UserInfo packageUserInfo(UserInfo userInfo) {
        String statusString=userInfo.getStatus().intValue()==0?"锁定":"正常";
        userInfo.getParam().put("statusString",statusString);
        String authStatusString = AuthStatusEnum.getStatusNameByStatus(userInfo.getAuthStatus());
        userInfo.getParam().put("authStatusString",authStatusString);
        return userInfo;
    }
}
